package com.cykj.controller;

import com.cykj.pojo.ExcelUser;
import com.cykj.service.AdminService;
import com.cykj.service.PatientService;
import com.cykj.util.JWTUtils;
import com.cykj.util.ResponseDto;
import com.cykj.util.excel.ExcelImportUtil;
import com.cykj.util.excel.ExcelOutputUtil;
import com.cykj.vo.*;
import io.jsonwebtoken.Claims;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private PatientService patientService;

    @RequestMapping("/deleteUsers")
    public ResponseDto deleteUsers(@RequestBody UserIdsVo vo) {
        System.out.println("-------------");
        System.out.println(vo.getIds());
        ResponseDto dto = adminService.deleteUserByIds(vo.getIds());
        return dto;
    }

    //@RequestMapping("/addUserByData")
    //public ResponseDto addUserByData(@RequestBody UserIdsVo vo){
    //    System.out.println(vo);
    //    ResponseDto dto = adminService.addUserByData(vo.getData());
    //    return dto;
    //}

    @RequestMapping("/selectByData")
    public ResponseDto selectByData(int sort, String value, int pageCurr, int pageSize) {
        ResponseDto dto = adminService.selectByData(sort, value, pageCurr, pageSize);
        return dto;
    }

    @RequestMapping("/login")
    public ResponseDto login(@RequestBody LoginVo vo, HttpSession session) {
        System.out.println(session.getAttribute("code"));
        //先判断验证码是否正确，正确在进行账号密码的判断
        if (vo.getCode().equals(session.getAttribute("code"))) {
            return adminService.login(vo.getAcc(), vo.getPwd());
        } else if (session.getAttribute("code") == null) {
            return new ResponseDto(-1, "验证码过期", null);
        } else {
            return new ResponseDto(2, "验证码错误", null);
        }
    }

    //批量上传
    @RequestMapping(value = "/upload")
    public void handleFileUpload(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
        //System.out.println("-------------------");
        //前端传入数据
        // 检查请求是否为多部分请求
        if (!ServletFileUpload.isMultipartContent(request)) {
            throw new ServletException("Content type is not multipart/form-data");
        }

        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            // 解析请求的内容提取文件数据
            List<FileItem> formItems = upload.parseRequest(request);

            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        //byte[] gbkBytes = fileName.getBytes("gbk");
                        //String name = new String(gbkBytes, "utf8");
                        //System.out.println("------------name"+fileName);
                        String filePath = request.getServletContext().getRealPath("/") + "WEB-INF" + File.separator + "static" + File.separator + fileName;
                        //System.out.println("-----------"+filePath);
                        File storeFile = new File(filePath);
                        //System.out.println("=======");
                        // 保存文件到硬盘
                        item.write(storeFile);
                        //到这边得到了数据
                        List<ExcelUser> users = ExcelImportUtil.readData(filePath);
                        System.out.println(users.size());
                        for (int i = 0; i < users.size(); i++) {
                            System.out.println(users.get(i));
                            String userName = users.get(i).getName();
                            int age = users.get(i).getAge();
                            String phone = users.get(i).getPhone();
                            String cardID = users.get(i).getCardID();
                            int height = users.get(i).getHeight();
                            int weight = users.get(i).getWeight();
                            int money = users.get(i).getMoney();
                            //1：男 2：女
                            String radio = null;
                            //System.out.println("============");
                            System.out.println(money);
                            if (users.get(i).getSex().equals("男")) {
                                radio = "1";
                            } else {
                                radio = "2";
                            }
                            patientService.addCommit(userName, age, phone, cardID, height, weight, radio, money);
                        }
                        request.setAttribute("message", "文件上传成功!");
                        storeFile.delete();
                    }
                }

            }
        } catch (Exception ex) {
            request.setAttribute("message", "文件上传失败!");
        }
    }

    //批量导出
    @RequestMapping("/download")
    public ResponseDto handleFileDownload(HttpServletResponse response) {
        try {
            //将东西全部弄进去，写入excel
            String classpath = getClass().getClassLoader().getResource("").getPath();
            //获取相对路径
            String newPathBase = classpath.substring(1, classpath.lastIndexOf("/WEB-INF/") + "/WEB-INF/".length());
            String newPath = newPathBase + "static/所有用户信息表.xlsx";
            newPath = newPath.replaceAll("/", "\\\\\\\\");
            adminService.handleFileDownload(newPath);
            //设置请求头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''所有用户信息表.xlsx"); // 注意：使用filename*来处理非ASCII文件名
            try (ServletOutputStream out = response.getOutputStream();
                 InputStream stream = new FileInputStream(newPath)) {//读取服务器上的文件
                byte buff[] = new byte[1024];
                int length;
                while ((length = stream.read(buff)) > 0) {
                    out.write(buff, 0, length);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return new ResponseDto(1, "导出成功", null);
        } catch (Exception e) {
            return new ResponseDto(0, "导出失败", null);
        }
    }

    @RequestMapping("/getAdminInfo")
    public ResponseDto getAdminInfo(String token) {
        //    解析token得到用户信息
        Claims claims = JWTUtils.parseJWT(token);
        return new ResponseDto(1, "成功", claims);
    }

    @RequestMapping("/reg")
    public ResponseDto register(@RequestBody RegVo vo, HttpSession session) {
        if (vo.getCode().equals(session.getAttribute("code"))) {
            return adminService.register(vo.getAcc(), vo.getPwd(), vo.getName(), vo.getRoleId());
        } else {
            return new ResponseDto(2, "验证码错误", null);
        }
    }

    @RequestMapping("forgetPwd")
    public ResponseDto forgetPwd(@RequestBody ForgetVo vo, HttpSession session) {
        if (vo.getCode().equals(session.getAttribute("code"))) {
            System.out.println(vo.getAcc() + vo.getName() + vo.getNewPwd() + vo.getRoleId());
            return adminService.forgetPwd(vo.getAcc(), vo.getName(), vo.getNewPwd(), vo.getRoleId());
        } else {
            return new ResponseDto(2, "验证码错误", null);
        }
    }

    @RequestMapping("/getAdmins")
    public ResponseDto getAdmins(@RequestBody AdminPageVo vo) {
        return adminService.getAdmins(vo.getPageCurr(), vo.getPageSize());
    }

    @RequestMapping("/getFace")
    public ResponseDto getFace(int id) {
        return adminService.getFace(id);
    }

    @RequestMapping("/alterPwd")
    public ResponseDto alterPwd(int id, String newPwd) {
        return adminService.alterPwd(id, newPwd);
    }

    @RequestMapping("/changeStatus")
    public ResponseDto changeStatus(int proStatus, int adminId) {
        if (proStatus == 2) {
            proStatus = 0;
        } else if (proStatus == 1) {
            proStatus = 1;
        }
        ResponseDto dto = adminService.changeStatus(proStatus, adminId);
        return dto;
    }

    @RequestMapping("/deleteAdmin")
    public ResponseDto deleteAdmin(int adminId) {
        return adminService.deleteAdmin(adminId);
    }

    @RequestMapping("/alterAdmin")
    public ResponseDto alterAdmin(int adminId, String adminName, String adminAccount, String departmentName, String roleName) {

        return adminService.alterAdmin(adminId, adminName, adminAccount, departmentName, roleName);
    }

    //添加人员
    @RequestMapping("/addCommit")
    public ResponseDto addCommit(String adminAccount, String adminPwd, String adminName, String roleName, String departmentName, String status) {
        return adminService.addCommit(adminAccount, adminPwd, adminName, roleName, departmentName, status);
    }
}
